      var customerTransactionGrid,grid;

      $(function(){
      $( "#tabs" ).tabs({
            collapsible: true
        });

              grid=  $("#customerGrid").jqGrid({
                url: "search",
                datatype: "json",
                mtype: "GET",
                colNames: ["Name", "Nick Name", "City","Phone Number","Mobile", "Company", 'Actions'],
                colModel: [
                    { name: "nickName", width: 125 },
                    { name: "name", width: 160 },
                    { name: "address.city", width: 80, align: "left" },
                    { name: "phoneNumber", width: 80, align: "left" },
                    { name: "mobileNumber", width: 80, align: "left" },
                    { name: "companyName", width: 150, align: "left" },
                    { name : 'customerId', index:'customerId', sortable:false,editable:false ,formatter:actionFormat, unformat:actionUnFormat,key:true},
                ],
                pager: "#customerGridPager",
                 postData: {
                        query: function() { return $("#search-name").val(); },
//                        customerType: function() { return $("#search-customerType").val(); }

                    } ,
                    toolbarfilter: true,
                rowNum: 10,
                rowList: [10, 20, 30],
                sortname: "customerId",
                sortorder: "desc",
                viewrecords: true,
                gridview: true,
                autoencode: true,
                caption: "Suppliers" ,
                height:400,
                autowidth : true,
                jsonReader : {root:"customers"},
                gridComplete: function(){
			        var ids = jQuery("#customerGrid").jqGrid('getDataIDs');
//                    for(var i=0;i < ids.length;i++){
//                        var cl = ids[i];
//                        be = "<button class='btn btn-xs btn-default btn-quick' title='Edit Row' onclick=\"jQuery('#customerGrid').editRow('"+cl+"');\"><i class='fa fa-pencil'></i></button>";
//                        se = "<button class='btn btn-xs btn-default btn-quick' title='Save Row' onclick=\"jQuery('#customerGrid').saveRow('"+cl+"');\"><i class='fa fa-save'></i></button>";
//                        ca = "<button class='btn btn-xs btn-default btn-quick' title='Cancel' onclick=\"jQuery('#customerGrid').restoreRow('"+cl+"');\"><i class='fa fa-times'></i></button>";
//                        jQuery("#customerGrid").jqGrid('setRowData',ids[i],{ act: be+se+ca });
//                    }
                }

                });

                  jQuery("#productGrid").jqGrid('navGrid', "#productGridPager", {
                    		edit : false,
                    		add : false,
                    		del : true
                    	});

                jQuery("a.get_selected_ids").bind("click", function() {
                		s = jQuery("#productGrid").jqGrid('getGridParam', 'selarrrow');

                	});



			 $( "#search-customer-btn").button().click(function () {

             	grid.trigger("reloadGrid");
			});

			$('#customerForm').modal({
                    keyboard: false ,
                    backdrop: false,
                    show: false
            })

             function actionFormat( cellvalue, options, rowObject ){
                          	return "<button class='btn btn-xs btn-default btn-quick' title='Edit Row' onclick=\"showDetails('"+cellvalue+"');\"><i class='fa fa-pencil'></i></button>"+
                          	"<button class='btn btn-xs btn-default btn-quick' title='Edit Row' onclick=\"showTransactionDetails('"+cellvalue+"');\"><i class='fa fa-list'></i></button>";

                        }
                        function actionUnFormat( cellvalue, options, cell){
                        	return $('img', cell).attr('src');
                        }
                         customerTransactionGrid=  $("#customerTransactionGrid").jqGrid({
                                        url: "transactionHistory",
                                        datatype: "local",
                                        mtype: "GET",
                                        colNames: ["Type", "Num", "Date","Amount"],
                                        colModel: [
                                            { name: "transactionType" ,align: "left" },
                                            { name: "transactionId" ,align: "left"},
                                            { name: "transactionDate", align: "left" },
                                            { name: "transactionAmount", align: "left" ,formatter:'currency' ,formatoptions:currencyformatoptions},

                                        ],
                                        pager: "#customerTransactionGridPager",
                                         postData: {
                                                transactionType: function() { return $("#search-transaction-type").val(); },
                                                dateRange: function() { return $("#search-transaction-dateRange").val(); },
                                                customerId: function() { return $("#trx-customerId").val(); }

                                            } ,
                                            toolbarfilter: true,
                                        rowNum: 10,
                                        rowList: [10, 20, 30],
                                        sortname: "transactionDate",
                                        sortorder: "desc",
                                        viewrecords: true,
                                        gridview: true,
                                        autoencode: true,
                                        caption: "Transactions" ,
                                        height:400,
                                        width : '800',
                                        footerrow : true,
                                                                                    userDataOnFooter : true,
                                                                                    toolbarfilter: true,
                                       jsonReader: {
                                                                                       root: 'transactions',
                                                                                      userdata: function (obj) {
                                                                                           return {
                                                                                               transactionAmount: obj.totalTransactionAmount
                                                                                           };
                                                                                       }
                                                                                   },
                                        gridComplete: function(){
                        			        var ids = jQuery("#customerGrid").jqGrid('getDataIDs');

                                        }

                                        });

               $("#search-transaction-type , #search-transaction-dateRange").on('change', function() {
                                  customerTransactionGrid.trigger("reloadGrid")
                            });


                $( "#search-customer" ).autocomplete({

                            source: function( request, response ) {
                            $.ajax({
                                      url: "search",
                                      dataType: "json",
                                      data: {
                                           query: request.term
                                            },
                                      success: function( data ) {
                                         response($.map(data.customers, function(item) {
                                                      return {
                                                      label: item.name+', '+item.address.city,
                                                      value: item.customerId,
                                                      customer:item,
                                                              }
                                                  }));
                                           }
                                        }); },
                                          minLength: 2,
                                                     select: function( event, ui ) {

                                                                        var customerInfo = ui.item.customer;
                                                                        $( "#customerId" ).val(customerInfo.customerId);
                                                                        $( "#customer-company" ).html(customerInfo.company);
                                                                        $( "#customer-name" ).html(customerInfo.name);
                                                                        $( "#customer-address" ).html(customerInfo.address.city);
                                                                        $( "#customer-mobile" ).html(customerInfo.mobile);
                                                                        $( "#customerinfo" ).hide();
                                                                        $( "#customerDetail" ).removeClass("hide");
                                                                        $(this).val(customerInfo.name);
                                                                        return true;
                                                            }
                                                            });

                                                          $( "#search-customer" ).autocomplete("option", "appendTo", "#customerinfo" );


              	                 $( "#customerDetailButton").button().click(function () {
                           	         $( "#customerinfo" ).show();
                                     $( "#customerDetail" ).addClass("hide");
              			        });

                                    function enableCustomerSearch(){
                                         $( "#customerinfo" ).show();
                                         $( "#customerDetail" ).addClass("hide");
                                    }




                        $('button.modelWindow').on('shown.bs.modal', function () {
                                 e.preventDefault();
                                 var title = $(this).data('title');
                                 $("#customer-payment-model-title").html(title);
                        });




                   $('#payment-form').validator().on('submit', function (event) {
                      if (event.isDefaultPrevented()) {
                        // handle the invalid form...
                      } else {
                            event.preventDefault();

                            var options = {
                                                    url:       'saveBillPayment' ,
                                                    type:      'post' ,
                                                    dataType:  'json' ,
                                                    clearForm: true  ,
                                                    resetForm: true  ,
                                                    timeout:   9000  ,
                                                    success:    function() {
                                                       grid.trigger("reloadGrid");

                                                        $('#customerForm').modal('hide')
                                                     }  ,
                                                      error:    function() {
                                                       alert('Error');
                                                     }
                                                };

                                                $("#payment-form").ajaxSubmit(options) ;
                                                return false;
                      }
                });

                $('#new-customer-form').validator().on('submit', function (event) {
                  if (event.isDefaultPrevented()) {
                    // handle the invalid form...
                  } else {
                    	event.preventDefault();

                    	var options = {
                                                url:       'save' ,
                                                type:      'post' ,
                                                dataType:  'json' ,
                                                clearForm: true  ,
                                                resetForm: true  ,
                                                timeout:   9000  ,
                                                success:    function() {
                                                   grid.trigger("reloadGrid");

                                                    $('#customerForm').modal('hide')
                                                 }  ,
                                                  error:    function() {
                                                   alert('Error');
                                                 }
                                            };

                    						$("#new-customer-form").ajaxSubmit(options) ;
                    						return false;
                  }
                });


//                             $('#new-customer-form1')
//                                    .formValidation({
//                                        framework: 'bootstrap',
//                                        icon: {
//                                            valid: 'glyphicon glyphicon-ok',
//                                            invalid: 'glyphicon glyphicon-remove',
//                                            validating: 'glyphicon glyphicon-refresh'
//                                        },
//                                        fields: {
//                                            nickName: {
//                                                validators: {
//                                                    notEmpty: {
//                                                        message: 'The full name is required'
//                                                    },
//                                                    regexp: {
//                                                        regexp: /^[a-zA-Z\s]+$/,
//                                                        message: 'The full name can only consist of alphabetical characters'
//                                                    }
//                                                }
//                                            },
//                                            email: {
//                                                validators: {
//                                                    notEmpty: {
//                                                        message: 'The email address is required'
//                                                    },
//                                                    emailAddress: {
//                                                        message: 'The email address is not valid'
//                                                    }
//                                                }
//                                            }
//
//                                        }
//                                    })
//                                    .on('success.form.fv', function(e) {
//                                        // Save the form data via an Ajax request
//                                        e.preventDefault();
//
//                                        var $form = $(e.target),
//                                            id    = $form.find('[name="id"]').val();
//
//                                        // The url and method might be different in your application
//                                        $.ajax({
//                                            url: 'http://jsonplaceholder.typicode.com/users/' + id,
//                                            method: 'PUT',
//                                            data: $form.serialize()
//                                        }).success(function(response) {
//                                            // Get the cells
//                                            var $button = $('button[data-id="' + response.id + '"]'),
//                                                $tr     = $button.closest('tr'),
//                                                $cells  = $tr.find('td');
//
//                                            // Update the cell data
//                                            $cells
//                                                .eq(1).html(response.name).end()
//                                                .eq(2).html(response.email).end()
//                                                .eq(3).html(response.website).end();
//
//                                            // Hide the dialog
//                                            $form.parents('.bootbox').modal('hide');
//
//                                            // You can inform the user that the data is updated successfully
//                                            // by highlighting the row or showing a message box
//                                            bootbox.alert('The user profile is updated');
//                                        });
//                                    });
    });




  function showTransactionDetails(index){


            $.ajax({url: "getDetails",
                dataType: "json",
                data: {
                        "customerId": index
                      },success: function(customerObj){
                            myApp.hidePleaseWait();
                            if(customerObj.customerId)
                               {
                                       loadFormData(customerObj,'customerTransaction');
                                        $('#customerTransaction > #model-title').text("Customer Information");
                                        $("#trx-customerId").val(index);
                                        customerTransactionGrid.jqGrid('setGridParam',{datatype: 'json'});
                                        customerTransactionGrid.trigger("reloadGrid");
                                        var options= {'keyboard':false,'show':true};
                                        $('#customerTransaction').modal(options);

                                }
                              else{

                                  }
                     }
               });


          }
         function showDetails(index){
                     myApp.showPleaseWait();
                         $.ajax({url: "getDetails", dataType: "json",data: {
                                           "customerId": index
                                 },success: function(productObj){
                                    myApp.hidePleaseWait();
                                   if(productObj.customerId)
                                   {
                                          loadFormData(productObj,'customerForm');
                                          $('#model-title').text("Edit Customer");
                                          var options= {'keyboard':false,'show':true};
                                          $('#customerForm').modal(options);
                                   }
                                    else{

                                    }

                               }});

          }



